<!--
 * @Description: 基建出库退库详情
 * @Version: 2.0
 * @Autor: gaofang
 * @Date: 2020-04-11 18:29:13
 * @LastEditors: jerry.zzy
 * @LastEditTime: 2021-08-07 16:36:54
-->
<template>
  <a-card>
    <p style="font-size: 18px; text-align: center">基建出库退库详情</p>
    <br />
    <a-form-model :model="Form" v-bind="layout"
      ><!-- 顶部的信息  -->
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号">
            <div>{{ Form.document }}</div>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="仓库名称">
            <div>{{ Form.storname }}</div>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="申请部门">
            <div>{{ Form.deptId_dictText }}</div>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="收发类别">
            <div>{{ Form.sendReceiveType_dictText }}</div>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="在建项目">
            <div>{{ Form.cprojectid_dictText }}</div>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库存组织">
            <div>{{ Form.pkCalbody_dictText }}</div>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="公司">
            <div>{{ Form.pkCorp_dictText }}</div>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库管员">
            <div>{{ Form.cwhsmanagerid_dictText }}</div>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务员">
            <div>{{ Form.cbizid_dictText }}</div>
          </a-form-model-item>
        </a-col>
        <!-- <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="业务流程">
            <div>{{ Form.cbiztype_dictText }}</div>
          </a-form-model-item>
        </a-col> -->

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据日期">
            <div>{{ Form.document_date }}</div>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="备注">
            <div>{{ Form.remark }}</div>
          </a-form-model-item>
        </a-col>

        <!-- <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库存组织">
            <div>{{ Form.pkCalbody_dictText }}</div>
          </a-form-model-item>
        </a-col> -->
      </a-row>

      <!-- <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
        <a-form-model-item label="业务流程">
          <div>{{ Form.cbiztype_dictText }}</div>
        </a-form-model-item>
      </a-col> -->
    </a-form-model>

    <a-table
      :columns="columns"
      :data-source="dataSource"
      style="margin-top: 10px"
      :pagination="false"
    >
    </a-table>

    <div style="margin-top: 20px">
      <!-- 单据 -->
      <a-form-model :model="Form" v-bind="layout"
        ><!-- 顶部的信息 -->
        <a-row>
          <!-- <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="负责人">
              <div>{{ Form.responsiblePerson }}</div>
            </a-form-model-item>
          </a-col> -->

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核人">
              <div>{{ Form.inspector }}</div>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期">
              <div>{{ Form.balance }}</div>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="制单人">
              <div>{{ Form.singleProducerName }}</div>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>

      <!-- 提交按钮组  
      1. 能审核提交的人是不能点击保存的
      2. 能保存的人是不能审核和提交的
      -->
      <div style="margin-top: 20px">
        <center>
          <a-button type="primary" style="margin-right: 20px" @click="goPrint">
            打印
          </a-button>

          <a-button style="margin-right: 20px" disabled> 保存 </a-button>

          <a-button
            @click="Examine"
            style="margin-right: 20px"
            :disabled="!alreadyCheckTag"
          >
            审核
          </a-button>

          <a-button
            @click="No_Examine"
            style="margin-right: 20px"
            :disabled="alreadyCheckTag"
          >
            反审核
          </a-button>

          <!-- <a-button
            type="primary"
            @click="Submit"
            style="margin-right: 20px"
            :disabled="!alreadyRecordTag"
          >
            提交
          </a-button> -->

          <a-button
            type="primary"
            @click="handleSaveButton"
            style="margin-right: 20px"
            
          >
            同步至用友
          </a-button>
        </center>
      </div>
    </div>

    <div style="display: none">
      <div id="printCons" style="width: 85%; margin: 0 auto; color: black">
        <!-- // 标题 -->
        <div
          id="style1"
          style="
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            height: 30px;
            line-height: 30px;
          "
        >
          <div style="margin-left: 10px">
            <div>单据号: {{ Form.document }}</div>
          </div>
          <div style="margin-left: 60px">
            <div>日期: {{ Form.document_date }}</div>
          </div>
          <div style="margin-left: 60px">
            <div>部门: {{ Form.deptId_dictText }}</div>
          </div>
        </div>
        <div
          id="style1"
          style="
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            height: 30px;
            line-height: 30px;
          "
        >
          <div style="margin-left: 10px">
            <div>收发类别: {{ Form.sendReceiveType_dictText }}</div>
          </div>
          <div style="margin-left: 10px">
            <div>在建项目: {{ Form.cprojectid_dictText }}</div>
          </div>
        </div>

        <!-- 表格 -->
        <div class="print-table" style="margin-top: 0px">
          <table
            style="width: 100%; text-align: center; border-collapse: collapse"
            border="0"
            cellspacing="0"
            cellpadding="0"
          >
            <tr>
              <th>存货名称</th>
              <th>单位</th>
              <th>规格</th>
              <th>实发数量</th>
              <th>单价</th>
              <th>金额</th>
              <th>备注</th>
            </tr>
            <tr v-for="(item, index) in printDataSource" :key="index">
              <th>{{ item.inventoryName }}</th>
              <th>{{ item.unit }}</th>
              <th>{{ item.standardModel }}</th>
              <th>{{ item.quantity }}</th>
              <th>{{ item.unitPrice }}</th>
              <th>{{ item.money }}</th>
              <th>{{ item.remark }}</th>
            </tr>
          </table>
        </div>

        <!-- 尾部信息 -->
        <div
          style="
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            height: 30px;
            line-height: 30px;
          "
        >
          <div style="margin-left: 10px">
            制单人： {{ Form.singleProducerName }}
          </div>
          <div style="margin-left: 80px">审核人： {{ Form.inspector }}</div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script>
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口
import moment from "moment";
import axios from "axios";
import printJS from "print-js";
let columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
    width: "80px",
  },
  // {
  //   title: "仓库编码",
  //   key: "depotNo",
  //   dataIndex: "depotNo",
  //   align: "center",
  // },
  // {
  //   title: "仓库名称",
  //   key: "depotName",
  //   dataIndex: "depotName",
  //   align: "center",
  // },
  // {
  //   title: "库位",
  //   key: "depotLocation",
  //   dataIndex: "depotLocation",
  //   align: "center",
  // },
  // {
  //   title: "仓位",
  //   key: "position",
  //   dataIndex: "position",
  //   align: "center",
  // },
  // {
  //   title: "所属单位",
  //   key: "storageUnit",
  //   dataIndex: "storageUnit",
  //   align: "center",
  // },
  {
    title: "存货编码",
    dataIndex: "invcode",
    key: "invcode",
    align: "center",
  },
  {
    title: "存货名称",
    dataIndex: "invname",
    key: "invname",
    align: "center",
  },
  {
    title: "规格型号",
    dataIndex: "invspec",
    key: "invspec",
    align: "center",
  },
  {
    title: "单位",
    key: "measname",
    dataIndex: "measname",
    align: "center",
  },
  {
    title: "辅助单位",
    key: "auxiliaryUnit",
    dataIndex: "auxiliaryUnit",
    align: "center",
  },
  {
    title: "退库数量",
    key: "quantity",
    dataIndex: "quantity",
    align: "center",
  },
  // {
  //   title: "单价",
  //   key: "unitPrice",
  //   dataIndex: "unitPrice",
  //   align: "center",
  // },
  // {
  //   title: "金额",
  //   key: "money",
  //   dataIndex: "money",
  //   align: "center",
  // },
  {
    title: "源单单号",
    key: "sourceNumber",
    dataIndex: "sourceNumber",
    align: "center",
  },
  // {
  //   title: "批次号",
  //   key: "batchNumber",
  //   dataIndex: "batchNumber",
  //   align: "center",
  // },
  // {
  //   title: "是否赠品",
  //   key: "giveaway",
  //   dataIndex: "giveaway",
  //   align: "center",
  //   width: "120px",
  // },
  // {
  //   title: "退库日期",
  //   key: "deliveryDate",
  //   dataIndex: "deliveryDate",
  //   align: "center",
  // },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
  },
];
export default {
  data() {
    return {
      //反审核：开始
      //保存关于反审核的信息
      isAntiAudit: [], //是否反审核
      isSynchronized: [], //是否同步
      savecoperator: "", //查询后获取操作员，删除用

      biaotouzhujian: "", //查询采购订单的表头主键

      all_list: [],
      isTongBu: false, //是否已经同步至用友。反审核时已经同步过了，再同步至用友就改为了更新同步至用友接口
      //反审核：结束
      printDataSource: [],
      u8c_array: [], //u8c传递数据表格的数据源
      arr: [], //销售订单子表
      arrOut: [], //销售出库单子表
      GeneralBillVO_46: [], //需给用友传递的data
      ayyanyany: [], //销售订单主表
      ayyanyanyOut: [], //销售出库单主表
      dataList: [], //u8c全部数据
      updateSucessRecordTag: false, //同步至u8c按钮的状态

      Form: {
        id: "", // id
        document: "", // 单据号
        document_date: "", // 单据日期
        depotName: "", // 仓库名称
        depotNo: "", // 仓库编号
        depotId: "", // 仓库Id
        storageUnit: "", // 所属单位名称
        storageUnitId: "", // 所属单位Id
        storageUnitNo: "", // 所属单位编号
        department: "", // 部门名称
        deptId: "", // 部门id
        client: "", // 客户名称
        clientId: "", // 客户Id
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: "", // 审核日期
        singleProducer: "", // 制单人名称
        singleProducerId: "", // 制单人Id
        cbiztype_dictText: "", // 业务流程名称
      },

      saleForm: {},
      // 格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      columns,
      dataSource: [],
      // autoSize: {
      //   x: 3500,
      //   y: 670,
      // },
      alreadyCheckTag: false, // 可以审核
      alreadyRecordTag: true, // 可以记账
    };
  },
  mounted() {
    this.initInfoMount();
  },
  watch: {
    $route() {
      this.initInfoMount();
    },
  },

  methods: {
    //————————————————————————————————反审核：开始——————————————————————
    //! 反审核
    async No_Examine() {
      if (this.isSynchronized == "已同步") {
        // fbillflag 单据状态 1删除 2自由(缺省) 3库房签字 4存货系统审核
        let _data = await this.purchaseInSign();
        console.log("_data", _data);
        // 使用 JSON.parse() 方法将数据转换为 JavaScript 对象。
        let flag = JSON.parse(_data.data).datas[0].parentvo.fbillflag;
        //查询后获取操作员，删除用
        this.savecoperator = JSON.parse(
          _data.data
        ).datas[0].parentvo.operator_code;
        console.log("查询后获取操作员，删除用", this.savecoperator);

        if (_data.status == "success") {
          if (flag == "4") {
            this.$message.error("已签字，反审核失败！");
          } else if (flag == "3") {
            this.$message.error("状态处于3");
            this.unsignMethod3();
          } else if (flag == "2") {
            this.$message.error("状态处于2");
            this.unsignMethod2();
          } else {
            this.$message.error("状态处于1");
            //直接反审核——>同步至用友（新增接口）
            this.update_audit("已反审核");
            this.save_u8c();
          }
        }
      } else {
        this.$message.success("未同步至用友，即将进行我方数据库反审核功能");
        //未同步至用友 直接进行反审核
        console.log("运行到11111111111111");
        this.postSynchronized("未同步");
        console.log("运行到222222222222222");

        this.update_audit("已反审核");
        this.$message.success("反审核成功！");

        console.log("运行到333333333333333");

        this.update_Mark(2);
        console.log("运行到444444444444444");

        // 跳转回列表页面
        this.$router.push("/infrasConsOutCancelList");
        console.log("运行到555555555555");
      }
    },

    // !采购入库单查询
    purchaseInSign() {
      this.isTongBu = false;

      // u8c接口
      return new Promise((resolve) => {
        axios({
          headers: {
            "Access-Control-Allow-Origin": "*",
            trantype: "code",
            "Content-Type": "application/json",
            usercode: "13355262265",
            password: "5ef208ee90e5504a7b569ebbd6342634",
            system: "test",
          },
          method: "post",
          url: "/api/u8cloud/api/ic/otherout/query",
          data: {
            billcode: this.Form.document, //单据号
            corp: "1001", //公司
            date_begin: this.Form.document_date, //起始日期
            date_end: this.Form.document_date, //结束日期
            inventory: "", //存货
            page_now: "1", //起始页
            warehouse: "", //仓库//! 不传了
          },
        }).then((response) => {
          resolve(response.data);
          console.log("返回的数据为::::", response.data);

          if (response.data.status == "success") {
            this.isTongBu = true;
            this.$message.success("查询成功");
          } else {
            this.$message.error(response.data.errormsg);
          }
        });
      });
    },

    //点击同步至用友
    async handleSaveButton() {
      console.log("this.isAntiAudit", this.isAntiAudit);
      console.log("this.isTongBu", this.isTongBu);
      let _data = await this.purchaseInSign();
      console.log("_data", _data);
      if (this.isTongBu) {
        this.unsignMethod3();
        this.postSynchronized("已同步");

        // this.update_u8c_yongyou();
      } else {
        this.save_u8c();
      }
      // if (this.isAntiAudit[0] == "已反审核") {
      //   console.log(" --- 触发修改 ---");
      //   this.update_u8c_yongyou();
      //   return;
      // }
      // console.log(" --- 触发新增 ---");
    },

    //! 调用采购订单审批接口就可以继续反审核了（否则不能再次反审核）
    update_u8c_approve() {
      axios({
        headers: {
          "Access-Control-Allow-Origin": "*",
          trantype: "code",
          "Content-Type": "application/json",
          usercode: "13355262265",
          password: "5ef208ee90e5504a7b569ebbd6342634",
          system: "test",
        },
        method: "post",
        url: "/api/u8cloud/api/pu/order/approve",
        data: {
          queryinfo: {
            date_end: this.Form.documentDate,
            date_begin: this.Form.documentDate,
            code: [this.Form.document],
            corp: "1001",
          },
          approveinfo: {
            approvid: "17864817161",
          },
        },
      }).then((response) => {
        if (response.data.status == "success") {
          // this.$message.success("采购订单审批成功");//todo 这个提示是准确的，下面的是用来提示的
          this.$message.success("同步成功");
          //同步至用友成功以后调用我们的接口修改同步字段为“已同步”
          this.postSynchronized("已同步");
          //如果弃审成功 就走更新是否反审核成功得标识
          this.update_audit("未反审核");
          // 跳转回列表页面
          this.$router.push("/infrasConsOutCancelList");
        } else {
          this.$message.error(response.data.errormsg);
        }
      });
    },

    //! 查询出表头主键
    searchcorderid() {
      return new Promise((resolve) => {
        axios({
          headers: {
            "Access-Control-Allow-Origin": "*",
            trantype: "code",
            "Content-Type": "application/json",
            usercode: "13355262265",
            password: "5ef208ee90e5504a7b569ebbd6342634",
            system: "test",
          },
          method: "post",
          url: "/api/u8cloud/api/pu/order/query",
          data: {
            date_end: this.Form.documentDate,
            page_size: 10,
            page_now: 1,
            date_begin: this.Form.documentDate,
            code: this.Form.document,
            corp: "1001",
          },
        }).then((response) => {
          resolve(response.data);
          // console.log("response",response.data.datas[0].parentvo.corderid);
          if (response.data.status == "success") {
            this.$message.success("查询成功");
            // 使用 JSON.parse() 方法将数据转换为 JavaScript 对象。
            let flag = JSON.parse(response.data).datas[0].parentvo.corderid;
            this.biaotouzhujian = flag;
            console.log("this.biaotouzhujian", this.biaotouzhujian);
          } else {
            this.$message.error(response.data.errormsg);
          }
        });
      });
    },
    //! 第一步 同步至用友成功以后调用我们的接口修改同步字段为“已/未同步”
    //是否同步标志位
    postSynchronized(isOrNo) {
      let data = {
        id: this.Form.id,
        isSynchronized: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //是否反审核标志位
    update_audit(isOrNo) {
      let data = {
        id: this.Form.id,
        isAntiAudit: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //审核标志位
    update_Mark(isOrNo) {
      let data = {
        id: this.Form.id,
        auditMark: isOrNo,
      };
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res);
      });
    },
    //当状态处于3时，调用取消签字接口——>我方进行反审核——>用友的相应单据的修改接口
    unsignMethod3() {
      axios({
        headers: {
          "Access-Control-Allow-Origin": "*",
          trantype: "code",
          "Content-Type": "application/json",
          usercode: "13355262265",
          password: "5ef208ee90e5504a7b569ebbd6342634",
          system: "test",
        },
        method: "post",
        url: "/api/u8cloud/api/ic/otherout/unsign",
        data: {
          queryInfo: {
            date_end: moment(this.Form.document_date).format("YYYY-MM-DD"),
            date_begin: moment(this.Form.document_date).format("YYYY-MM-DD"),
            billcode: this.Form.document,
            corp: "1001",
          },
          unsignInfo: {
            coperator: this.u8c_array[0][0].singleProducerByCode_dictText,
            // coperator: this.$store.state.user.info.id,
          },
        },
      }).then((response) => {
        if (response.data.status == "success") {
          // this.$message.success("采购订单审批成功");//todo 这个提示是准确的，下面的是用来提示的
          this.$message.success("取消签字成功！");
          // this.$message.success("同步成功");
          //同步至用友成功以后调用我们的接口修改同步字段为“已同步”
          // this.postSynchronized("已同步");
          //如果弃审成功 就走更新是否反审核成功得标识

          this.update_u8c_yongyou(); //反审核的用友修改接口
          this.update_audit("已反审核"); //我方反审核

          // 跳转回列表页面
          this.$router.push("/infrasConsOutCancelList");
        } else {
          this.$message.error(response.data.errormsg);
        }
      });
    },
    //当状态处于2时，调用我方进行反审核——>用友的相应单据的修改接口——>取消签字接口
    unsignMethod2() {
      //我方进行反审核
      this.update_audit("已反审核");
      //用友的相应单据的修改接口
      this.update_u8c_yongyou();
      //取消签字接口
      axios({
        headers: {
          "Access-Control-Allow-Origin": "*",
          trantype: "code",
          "Content-Type": "application/json",
          usercode: "13355262265",
          password: "5ef208ee90e5504a7b569ebbd6342634",
          system: "test",
        },
        method: "post",
        url: "/api/u8cloud/api/ic/otherout/unsign",
        data: {
          queryinfo: {
            date_end: this.Form.documentDate,
            date_begin: this.Form.documentDate,
            billcode: this.Form.document,
            corp: "1001",
          },
          unsignInfo: {
            coperator: this.$store.state.user.info.id,
          },
        },
      }).then((response) => {
        if (response.data.status == "success") {
          // this.$message.success("采购订单审批成功");//todo 这个提示是准确的，下面的是用来提示的
          this.$message.success("取消签字成功！");
          // this.$message.success("同步成功");
          //同步至用友成功以后调用我们的接口修改同步字段为“已同步”
          // this.postSynchronized("已同步");
          //如果弃审成功 就走更新是否反审核成功得标识

          // this.update_audit("未反审核");//我方反审核
          // this.update_u8c_yongyou();//反审核的用友修改接口
          // 跳转回列表页面
          this.$router.push("/infrasConsOutCancelList");
        } else {
          this.$message.error(response.data.errormsg);
        }
      });
    },
    //反审核的用友修改接口
    update_u8c_yongyou() {
      console.log("111111111111111111111");
      this.ayyanyany = [];
      console.log(this.saleForm, "this.saleForm");
      console.log("this.dataList", this.dataList);
      //todo:已审核后才可以调用
      if (this.dataList[0].auditMark_dictText == "已审核") {
        console.log("22222222222222222");

        for (let i = 0; i < this.u8c_array.length; i++) {
          this.arr = [];
          for (let j = 0; j < this.u8c_array[i].length; j++) {
            let data = {
              cinventoryid: this.u8c_array[i][j].invcode, //存货ID
              noutnum: this.u8c_array[i][j].quantity, //实出数量
              dbizdate: moment(this.u8c_array[i][j].deliveryDate).format(
                "YYYY-MM-DD"
              ), //业务日期
            };
            this.arr.push(data);
            console.log("this.arr", this.arr);
          }
          this.ayyany = {
            parentvo: {
              cdispatcherid: this.u8c_array[i][0].sendReceiveType1_dictText, //收发类别名称
              cdptid: this.u8c_array[i][0].cdptidByCode_dictText, // 部门名称
              coperatorid: this.u8c_array[i][0].singleProducerByCode_dictText, //制单人
              cwhsmanagerid: this.u8c_array[i][0].cwhsmanagerid1_dictText, //!库管员---
              cbizid: this.u8c_array[i][0].workNO, //!业务员---
              cwarehouseid: this.u8c_array[i][0].storcode, //仓库
              dbilldate: moment(this.u8c_array[i][0].documentDate).format(
                "YYYY-MM-DD"
              ), //单据日期
              vbillcode: this.u8c_array[i][0].document, //单据号
              pk_calbody: "100001", //库存组织PK=仓库编号
              pk_corp: "1001", //公司
              cprojectid: this.u8c_array[i][0].cprojectid1_dictText, //!项目
            },
            childrenvo: this.arr,
          };
          this.ayyanyany.push(this.ayyany);
        }
        //U8c
        axios({
          headers: {
            "Access-Control-Allow-Origin": "*",
            trantype: "code",
            "Content-Type": "application/json",
            usercode: "13355262265",
            password: "5ef208ee90e5504a7b569ebbd6342634",
            system: "test",
          },
          method: "post",
          url: "/api/u8cloud/api/ic/otherout/update",
          data: {
            GeneralBillVO_4I: this.ayyanyany,
          },
        }).then((response) => {
          console.log("response1111333333333333", response.data);
          if (response.data.status == "success") {
            console.log("进入了if");
            this.$message.success("同步成功！");

            //同步至用友成功以后调用我们的接口修改同步字段为“已同步”
            this.postSynchronized("已同步");
            this.updateSucessRecordTag = true;
            // 跳转回列表页面
            this.$router.push("/infrasConsOutCancelList");
          } else {
            console.log("进入了else");

            console.log("44444444444444444444");
            this.$message.error(response.data.errormsg);

            // this.$message.error(response.data.errormsg);
          }
        });
      } else {
        this.$message.error("请先审核，再进行同步！");
      }
    },
    //————————————————————————————————反审核：结束——————————————————————
    //——————————————————————————同步至用友开始————————————————————
    getAccount(data, array) {
      const type = function (o) {
        var s = Object.prototype.toString.call(o);
        return s.match(/\[object (.*?)\]/)[1].toLowerCase();
      };
      const that = this;
      var sum = "";
      comHttp.getReceiveSendTypeByName("?name=" + data).then((res) => {
        this.temporaryForm = res.result;
        for (let i = 0; i < array.length; i++) {
          for (
            let j = 0;
            j < this.temporaryForm.accountingSubjects.length;
            j++
          ) {
            this.getAfficate(
              this.temporaryForm.accountingSubjects[j],
              i,
              that,
              array
            );
          }
          for (let j = 0; j < res.result.abstractType.length; j++) {
            let findArr = res.result.abstractType[j].type;
            let [objName, argumentName] = findArr.split(".");

            let taget = this[objName];

            if (type(taget) == "object") {
              sum += taget[argumentName];
            } else if (type(taget) == "array") {
              sum += taget[i][argumentName];
            } else if (type(findArr) == "string") {
              sum += findArr;
            }
          }
          this.arr.push(sum);
          sum = "";
        }
      });
    },
    getAfficate(subData, index, that, list) {
      axios({
        headers: {
          "Access-Control-Allow-Origin": "*",
          "Content-Type": "application/json",
          usercode: "13355262265",
          password: "5ef208ee90e5504a7b569ebbd6342634",
          system: "test",
        },
        method: "post",
        url: "/proxy/u8cloud/api/uapbd/accsubj/query",
        data: {
          pk_subjscheme: "0003",
          unitcode: "5001",
          subjcode: subData.value,
        },
      }).then(function (response) {
        that.ass = [];
        for (
          let i = 0;
          i < JSON.parse(response.data.data).datas[0].m_vecSubjAss.length;
          i++
        ) {
          that.ass.push({
            checktypecode: JSON.parse(response.data.data).datas[0].m_vecSubjAss[
              i
            ].bdcode, //辅助核算编码  接口调用
            checkvaluecode: that.getSupplementaryAccounting(
              JSON.parse(response.data.data).datas[0].m_vecSubjAss[i].bdname,
              index
            ), //辅助核算的值 编码
          });
        }

        that.details.push({
          creditamount:
            subData.type == 1 && subData.checkValue.indexOf("金额") != -1
              ? 1.3
              : 0.0, //金额
          creditquantity:
            subData.type == 1 && subData.checkValue.indexOf("数量") != -1
              ? list[index].quantity
              : "", //数量
          debitamount:
            subData.type == 2 && subData.checkValue.indexOf("金额") != -1
              ? 1.2
              : 0.0, //金额
          debitquantity:
            subData.type == 2 && subData.checkValue.indexOf("数量") != -1
              ? list[index].quantity
              : "", //数量
          excrate2: "6.0", //
          explanation: that.arr[index], //摘要
          localcreditamount:
            subData.type == 1 && subData.checkValue.indexOf("金额") != -1
              ? 1.3
              : 0.0, //金额
          localdebitamount:
            subData.type == 2 && subData.checkValue.indexOf("金额") != -1
              ? 2.0
              : 0.0,
          pk_accsubj: subData.value, //科目编码  接口获取
          pk_currtype: "CNY", //币种编码  接口获取
          price: 0.5, //单价
          ass: that.ass,
          cashflow: [
            {
              money: "金额", //金额
            },
          ],
        });

        console.log(that.details);
      });
    },
    getSupplementaryAccounting(name, index) {
      if (name == "存货分类") {
        return this.DataSource[index].inventoryNo;
      }

      if (name == "仓库档案") {
        return this.DataSource[index].depotNo;
      }
      if (name == "存货辅助核算") {
        return this.DataSource[index].inventoryNo;
      }
    },
    //同步至用友
    save_u8c() {
      this.ayyanyany = [];

      console.log("this.u8c_array", this.u8c_array);
      for (let i = 0; i < this.u8c_array.length; i++) {
        console.log("i", i);

        this.arr = [];

        for (let j = 0; j < this.u8c_array[i].length; j++) {
          console.log("j", j);
          console.log("this.u8c_array[i].length", this.u8c_array[i].length);
          let data = {
            cinventoryid: this.u8c_array[i][j].invcode, //存货id √
            noutnum: -this.u8c_array[i][j].quantity, //实出数量 √
            nshouldoutnum: -this.u8c_array[i][j].quantity, //应出数量 √
            dbizdate: moment(this.u8c_array[i][j].deliveryDate).format(
              "YYYY-MM-DD"
            ), // 业务日期-出库日期 √
            vnotebody: this.u8c_array[i][j].remark, //行备注
          };
          this.arr.push(data);
          console.log("this.arr", this.arr);
        }
        this.GeneralBillVO_46 = {
          parentvo: {
            breturn: "Y", //是否退货
            coperatorid: this.u8c_array[i][0].singleProducerByCode_dictText, //制单人id √
            cwhsmanagerid: this.u8c_array[i][0].cwhsmanagerid1_dictText, // 库管员 √
            cbizid: this.u8c_array[i][0].workNO, //业务员 √
            ccustomerid: this.u8c_array[i][0].clientIdByCode_dictText, //客户 √
            pk_defdoc3: this.u8c_array[i][0].farmer1_dictText, //自定义项3-农户 √
            cotherwhid: "", //!其他仓库（入库仓库）√
            cwarehouseid: this.u8c_array[i][0].storcode, //仓库id√
            cdptid: this.u8c_array[i][0].cdptidByCode_dictText, //部门 √
            dbilldate: moment(this.u8c_array[i][0].documentDate).format(
              "YYYY-MM-DD"
            ), //单据日期√
            vbillcode: this.u8c_array[i][0].document, //单据号√
            cdispatcherid: this.u8c_array[i][0].sendReceiveType1_dictText, //收发类别id-
            pk_calbody: "100001", //库存组织编码×××××
            pk_corp: "1001", //公司编码×××××
            vnote: "", //备注×××××
          },
          childrenvo: this.arr,
        };

        this.ayyanyany.push(this.GeneralBillVO_46);
      }
      // u8c接口
      axios({
        headers: {
          "Access-Control-Allow-Origin": "*",
          trantype: "code",
          "Content-Type": "application/json",
          usercode: "13355262265",
          password: "5ef208ee90e5504a7b569ebbd6342634",
          system: "test",
        },
        method: "post",
        url: "/api/u8cloud/api/ic/otherout/save/sign",
        data: {
          GeneralBillVO_4I: this.ayyanyany,
        },
      }).then((response) => {
        console.log("返回的数据为::::", response.data);
        if (response.data.status == "success") {
          this.$message.success("同步成功");
          //同步至用友成功以后调用我们的接口修改同步字段为“已同步”
          this.postSynchronized("已同步");
          this.updateSucessRecordTag = true;
          this.$router.push("/infrasConsOutCancelList");
        } else {
          console.log("进入");
          // this.update_u8c_yongyou(); //todo 新增失败的话尝试走一下修改， 这个功能还需要再完善，因为这样不会返回失败的信息。
          //todo 这里要解决一个问题： 反审核完成之后进来这个页面，是已经第二次同步了，已经不是新增了，但是根据其余的标志位无法进行判断是新增还是修改
          // alert(response.data.errormsg);
          this.$message.error(response.data.errormsg);
        }
      });
    },

    //this.u8c_array数组根据仓库编码筛选，将相同仓库编码的项归纳为一个数组
    sortArr(arr, str) {
      var newArr = [],
        newArrItem = [],
        _any;

      arr = arr.sort(function (a, b) {
        var s = a[str],
          t = b[str];

        return s < t ? -1 : 1;
      });
      if (arr.length) {
        _any = arr[0][str];
      }
      for (var i in arr) {
        if (arr[i][str] === _any) {
          newArrItem.push(arr[i]);
        } else {
          _any = arr[i][str];
          newArr.push(newArrItem);
          newArrItem = [arr[i]];
        }
      }
      newArr.push(newArrItem);
      this.u8c_array = newArr;
      console.log("u8c_array", this.u8c_array);
    },

    //
    initInfoMount() {
      if (typeof this.$route.query.Id != "undefined") {
        console.log("--------- 更新视图 销售退库  ----------");
        this.setInitInfo(this.$route.query.Id);
      }
    },

    // 审核函数
    Examine() {
      // this.Form.balance = moment().format("YYYY-MM-DD");
      console.log(this.Form.balance);
      let data = {
        id: this.Form.id,
        auditMark: 1,
        balance: this.Form.balance,
      };

      // 提交审核信息，修改表一数据
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        if (res.code == 200) {
          this.$message.success("审核成功");
          this.alreadyCheckTag = false;
          this.updateSucessRecordTag = false;
        } else {
          this.$message.success("审核失败");
        }
      });
    },

    //——————————————————————————同步至用友结束————————————————————
    //————————————————————————————————打印开始——————————————————————————
    getPrint() {
      this.printDataSource = [];
      let sum = 0;
      console.log("data", this.data);
      for (let i = 0; i < this.dataSource.length; i++) {
        let data = {
          inventoryName: this.dataSource[i].invname, //存货名称
          unit: this.dataSource[i].unit, //单位
          standardModel: this.dataSource[i].measname, //规格
          quantity: this.dataSource[i].quantity, //数量
          money: this.dataSource[i].money, //金额
          remark: this.dataSource[i].remark, // 备注
        };
        sum = sum + this.dataSource[i].quantity;
        this.printDataSource.push(data);
      }

      // 计算合计
      let endData = {
        inventoryName: "合计",
        unit: "",
        standardModel: "",
        quantity: sum,
        unitPrice: "",
        money: "",
        remark: "",
      };
      this.printDataSource.push(endData);
    },
    // 打印功能实现
    goPrint() {
      const style = "@page {margin:0 10mm}; "; // 去掉页眉和页脚
      printJS({
        style, // 添加去掉页眉页脚样式
        targetStyles: ["*"],
        type: "html", // 类型
        printable: "printCons", // 表格内容
        maxWidth: 1000,
        // 表头
        header: ` 
        <h3  style="
            padding-top:10px;
            text-align: center;
            height: 40px;
            line-height: 40px;
            font-size: 20px;
          ">基建出库退库单</h3>
       `,
        // 表格属性及内容
        // properties: [
        //   { field: "inventoryNo", displayName: "存货编码", columnSize: `10%` },
        //   {
        //     field: "inventoryName",
        //     displayName: "存货名称",
        //     columnSize: `30%`,
        //   },
        //   { field: "standardModel", displayName: "规格", columnSize: `20%` },
        //   { field: "unit", displayName: "单位", columnSize: `10%` },
        //   { field: "quantity", displayName: "数量", columnSize: `10%` },
        //   { field: "remark", displayName: "备注", columnSize: `20%` },
        // ],
        // gridHeaderStyle: "border: 1px solid #000;text-align:center", // 表头公用样式
        // gridStyle: "border: 1px solid #000;text-align:center;height:20px", // 表格公用样式
        // 默认字体置中,高度20
      });
    },
    //————————————————————————————————打印结束——————————————————————————
    //

    // 路由跳转,设置初始化信息
    setInitInfo(id) {
      //反审核标志位重置
      this.isAntiAudit = [];
      this.isSynchronized = [];

      comHttp
        .getInOrOutStorageOrderAndGoodsInfoById("?id=" + id)
        .then((res) => {
          this.isSynchronized = res.result.list[0].isSynchronized; //是否同步至用友

          this.dataSource = [];
          console.log("通过Id查询出来的信息::::", res);

          if (res.result.list[0].auditMark == 2) {
            this.alreadyCheckTag = true; // 未审核
          } else {
            this.alreadyCheckTag = false; // 已审核
          }

          console.log(res);
          this.Form = {};
          this.dataSource = [];
          /* ------------- 设置表单信息 -------------- */
          this.Form.id = res.result.list[0].id;
          this.Form.document = res.result.list[0].document;
          this.$set(
            this.Form,
            "document_date",
            res.result.list[0].documentDate
          );
          // 仓库名称
          this.Form.storname = res.result.list[0].storname;
          // 部门
          this.Form.deptId_dictText = res.result.list[0].deptId_dictText;
          // 所属仓库

          // 客户
          // this.Form.clientId_dictText = res.result.list[0].clientId_dictText;
          // 业务类型
          this.Form.cbiztype_dictText = res.result.list[0].cbiztype_dictText;

          // 库管员
          this.Form.cwhsmanagerid_dictText =
            res.result.list[0].cwhsmanagerid_dictText;

          // 库存组织
          this.Form.pkCalbody_dictText = res.result.list[0].pkCalbody_dictText;

          // 收发类别
          this.Form.sendReceiveType_dictText =
            res.result.list[0].sendReceiveType_dictText;

          // 在建项目
          this.Form.cprojectid_dictText =
            res.result.list[0].cprojectid_dictText;

          // 公司
          this.Form.pkCorp_dictText = res.result.list[0].pkCorp_dictText;

          // 库管员
          this.Form.cwhsmanagerid_dictText =
            res.result.list[0].cwhsmanagerid_dictText;

          // 业务员
          this.Form.cbizid_dictText = res.result.list[0].cbizid_dictText;

          // 备注
          this.Form.remark = res.result.list[0].remark;

          // 审核人
          this.$set(this.Form, "inspectorId", res.result.list[0].inspector);
          this.$set(
            this.Form,
            "inspector",
            res.result.list[0].inspector_dictText
          );

          // 制单人
          this.Form.singleProducerName =
            res.result.list[0].singleProducer_dictText;

          let i = 0;
          res.result.list.forEach((element) => {
            let data = {
              id: element.twoId,
              key: i + 1,
              invname: element.invname,
              invcode: element.invcode,
              invspec: element.invspec,
              measname: element.measname,
              auxiliaryUnit: element.auxiliaryUnit_dictText,
              sourceNumber: element.sourceNumber,
              remark: element.remarks,
              quantity: element.quantity,
              isAntiAudit: element.isAntiAudit,
              isSynchronized: element.isSynchronized,
            };
            i = i + 1;
            this.dataSource.push(data);
            this.isAntiAudit.push(data);
            // this.isSynchronized.push(data);
          });
          this.dataList = res.result.list;

          this.getPrint();
          this.getAccount(this.Form.sendReceiveType, res.result.list);
          //用友接口需要的数据
          this.sortArr(res.result.list, "depotNo");
        });
    },
  },
};
</script>

<style>
.print-table table td,
.print-table table th,
.print-table table tr {
  border: 1px solid black;
}
.print-table table tr {
  height: 30px;
}
.print-table table th {
  height: 30px;

  font-weight: normal;
}
</style>
